package com.maoye.ossp.biz.intent.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.hotent.base.core.util.string.StringUtil;
import com.hotent.base.db.api.IdGenerator;
import com.maoye.ossp.biz.contract.entity.AdvertAssociated;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.ResultSapVo;
import com.maoye.ossp.biz.contract.service.IAdvertAssociatedService;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.utils.ContractUtils;
import com.maoye.ossp.biz.contract.utils.JacksonUtils;
import com.maoye.ossp.biz.intent.entity.IntAssbaseitems;
import com.maoye.ossp.biz.intent.entity.IntAssbrands;
import com.maoye.ossp.biz.intent.entity.IntAssitems;
import com.maoye.ossp.biz.intent.entity.IntAssociated;
import com.maoye.ossp.biz.intent.entity.IntAssshops;
import com.maoye.ossp.biz.intent.service.IIntAdvertociatedService;
import com.maoye.ossp.biz.intent.service.IIntAssociatedService;
import com.maoye.ossp.biz.negotiation.entity.Assinfo;
import com.maoye.ossp.biz.negotiation.entity.Assrecords;
import com.maoye.ossp.biz.negotiation.service.AssinfoService;
import com.maoye.ossp.biz.negotiation.service.AssrecordService;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.service.IDataBean;
import com.maoye.ossp.common.util.ApplicationContextUtils;
import com.maoye.ossp.common.util.RequestContext;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.SysBaseFormat;
import com.maoye.ossp.sys.base.service.ICMCateService;
import com.maoye.ossp.sys.base.service.SysBaseFormatService;
import com.maoye.ossp.sys.base.service.SysBaseShopService;
import com.maoye.ossp.sys.base.utils.SysDictUtils;
import com.maoye.ossp.sys.msg.entity.TodoMessage;
import com.maoye.ossp.sys.msg.handler.MsgStrategyContext;
import com.maoye.ossp.sys.msg.util.MessageConstant;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
import com.maoye.sc.service.user.UserServiceImpl;

/**
 * 对象功能:联营合同意向（新签、续签、变更、反馈）  控制器类
 * 开发公司:MOI
 * 开发人员:yanghao
 * 创建时间:2014-02-20 14:50:38
 */

@Controller
@RequestMapping("biz/intent/intAdvertociated")
public class intAdvertociatedController extends BaseController {
	@Resource
	MsgStrategyContext messageService;
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private IIntAssociatedService intAssociatedService;
	@Resource
	IIntAdvertociatedService intAdvertociatedService;
	@Resource
	private IContractService  contractServce;
	@Resource
	IAdvertAssociatedService iAdvertAssociatedService;
	@Resource
	private AssrecordService assrecordService;
	@Resource
	public IdGenerator idGenerator;
	
	@Resource
	SysBaseFormatService sysBaseFormatService;
	
	@Resource
	SysBaseShopService sysBaseShopService;
	@Resource
	private ICMCateService icmCateService;
	
	@Resource
	AssinfoService assinfoService;
	
	@Resource
	private UserServiceImpl  userServiceImpl;
	
	@RequestMapping(value = "list")
	public String list( IntAssociated intAssociated,Model mode, HttpServletRequest request) {
		QueryFilter queryFilter = getQuerFilter(request, intAssociated);
		queryFilter.addFilter("area", intAssociated.getArea(), QueryOP.EQUAL);
		queryFilter.addFilter("areaId", intAssociated.getAreaId(), QueryOP.EQUAL);
		queryFilter.addFilter("store", intAssociated.getStore(), QueryOP.EQUAL);
		queryFilter.addFilter("storeId", intAssociated.getStoreId(), QueryOP.EQUAL);
		queryFilter.addFilter("storeId", intAssociated.getStoreId(), QueryOP.EQUAL);
		queryFilter.addFilter("floor", intAssociated.getFloor(), QueryOP.EQUAL);
		queryFilter.addFilter("floorId", intAssociated.getFloorId(), QueryOP.EQUAL);
		queryFilter.addFilter("intentType", intAssociated.getIntentType(), QueryOP.EQUAL);
		queryFilter.addFilter("intentNo", intAssociated.getIntentNo(), QueryOP.EQUAL);
		queryFilter.addFilter("isContractModify", intAssociated.getIsContractModify(), QueryOP.EQUAL);
		queryFilter.addFilter("isModifyContract", intAssociated.getIsModifyContract(), QueryOP.EQUAL);
		queryFilter.addFilter("isCreateContract", intAssociated.getIsCreateContract(), QueryOP.EQUAL);
		String createBy = null;
		if(StringUtil.isNotEmpty(intAssociated.getCreateBy())){
			createBy = ContractUtils.getUserId(intAssociated.getCreateBy());
		}
		User user=userServiceImpl.getUserById(UserUtils.getCurrentUserId().toString());
		String userType= user.getUserType();
		if(ContractUtils.USER_TYPE_S.equals(userType)){
			queryFilter.addFilter("supplierId",user.getId().toString(), QueryOP.EQUAL);
		}
		queryFilter.addFilter("createBy", createBy, QueryOP.EQUAL);
		queryFilter.addFilter("status", intAssociated.getStatus(), QueryOP.EQUAL);
		queryFilter.addFilter("startDate", intAssociated.getStartDate(), QueryOP.EQUAL);
		queryFilter.addFilter("endDate", intAssociated.getEndDate(), QueryOP.EQUAL);
		queryFilter.addFilter("contractType", ContractUtils.CONTRACT_TYPE_GG, QueryOP.EQUAL);
		Page<IntAssociated> page =null;
		if(intAssociated.getIntAssbrandsList() !=null && !intAssociated.getIntAssbrandsList().isEmpty() ){
			IntAssbrands brand = intAssociated.getIntAssbrandsList().get(0);
			if(StringUtil.isNotEmpty(brand.getBrandCName()) ){
				queryFilter.addFilter("brandCName", intAssociated.getIntAssbrandsList().get(0).getBrandCName(), QueryOP.EQUAL);
				mode.addAttribute("brandCName", intAssociated.getIntAssbrandsList().get(0).getBrandCName());
				page = (Page<IntAssociated>) intAssociatedService.find1(queryFilter);
			}else{
				page = (Page<IntAssociated>) intAssociatedService.find(queryFilter);
			}
		}else{
			 page = (Page<IntAssociated>) intAssociatedService.find(queryFilter);
		}
		int totalSize = (page.getTotal() + page.getPageSize() - 1) / page.getPageSize();
		mode.addAttribute("page", page);
		mode.addAttribute("totalSize", totalSize);
		mode.addAttribute("intAssociated", intAssociated);
		return resultPage("/biz/intent/intAdvertociated/list", mode, request); 
	}
	/**
	 * 保存意向
	 * @param model
	 * @param intAssociated
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author yanghao
	 * @data 2014年5月28日
	 */
	@SuppressWarnings("serial")
	@RequestMapping(value = "save")
	public String save( Model model,IntAssociated intAssociated,RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response) throws Exception {
		String navId = request.getParameter("navId");
		intAssociatedService.save(intAssociated);
		Map<String, Object> map = new HashMap<String, Object>();
		Assrecords assrecords = assrecordService.get(intAssociated.getNegotiationId()) ;
		map.put("id", assrecords.getAssinfo().getId());
		map.put("status", ContractUtils.NEG_STATUS_YTJ);
		assinfoService.updateStatus(map);
		addMessage(redirectAttributes, "保存'" + intAssociated.getSubject()+ "意向合同'成功");
		return "redirect:/biz/intent/intAdvertociated/list?navId="+navId;
	}
	
	
	/**
	 * 提交意向
	 * @param model
	 * @param intAssociated
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年5月28日
	 */
	@SuppressWarnings("serial")
	@RequestMapping(value = "submit")
	public String submit( Model model,IntAssociated intAssociated,RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response) throws Exception {
		String navId  = request.getParameter("navId");
		intAssociatedService.submit(intAssociated);
		Map<String, Object> map = new HashMap<String, Object>();
		Assrecords assrecords = assrecordService.get(intAssociated.getNegotiationId()) ;
		map.put("id", assrecords.getAssinfo().getId());
		map.put("status", ContractUtils.NEG_STATUS_YTJ);
		assinfoService.updateStatus(map);
		addMessage(redirectAttributes, "提交'" + intAssociated.getSubject()+ "意向合同'成功");
		return "redirect:/biz/intent/intAssociated/list?navId="+navId;
	}
	/**
	 * 跳转到新增联营合同意向页面 
	 * @param intAssociated
	 * @param request
	 * @param model
	 * @return
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年3月31日
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "{assrecordsId}/add")
	public String add(@PathVariable Long assrecordsId,IntAssociated intAssociated,HttpServletRequest request, Model model) throws Exception {
		model = intAdvertociatedService.init(assrecordsId, model);
		return resultPage("/biz/intent/intAdvertociated/add", model, request);
	}

	@RequestMapping(value = "{id}/edit")
	public String edit(@PathVariable Long id,HttpServletRequest request,  Model model) {
		model= intAssociatedService.edit(id,model);
		
		return resultPage("/biz/intent/intAdvertociated/add", model, request);
	}
	/**
	 * 批量删除意向合同
	 * @param ids
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @author yanghao
	 * @data 2014年5月22日
	 */
	@RequestMapping(value = "{ids}/removeBatch")
	public String removeBatch(@PathVariable String ids, HttpServletRequest request,Model model,RedirectAttributes redirectAttributes) {
		String navId = request.getParameter("navId");
		intAssociatedService.removeBatch(ids);
		redirectAttributes.addFlashAttribute(navId);
		return "redirect:/biz/intent/intAdvertociated/list?navId="+navId;
	}
	/**
	 * 展示意向合同详细信息
	 * @param id
	 * @param model
	 * @return
	 * @author yanghao
	 * @data 2014年5月23日
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "{id}/view")
	public String view(@PathVariable Long id,HttpServletRequest request, Model model) {
		IntAssociated intAssociated = intAssociatedService.get(id);
		Long lastContractId =  intAssociated.getContractId();
		if(lastContractId !=null){
			AssociatedContract  lastContract = contractServce.get(lastContractId.toString());
			model.addAttribute("associated", lastContract);
		}
		SysBaseFormat format = sysBaseFormatService.getFormatByCode(intAssociated.getFormatId());
		StringBuilder shopName = new StringBuilder();
		List<IntAssshops>  assshopsList =  intAssociated.getIntAssshopsList();
		Long contractId =  intAssociated.getContractId();
		if(contractId != null){
			AdvertAssociated  associated = iAdvertAssociatedService.get(contractId.toString());
			if(associated!=null){
			model.addAttribute("associated", associated);
			associated.setVersionUrl("biz/intent/intAdvertociated/");
			}
		}
		if(assshopsList !=null && assshopsList.size()>0){
			for (int i = 0; i < assshopsList.size(); i++) {
				shopName.append(assshopsList.get(i).getShop());
				shopName.append(",");
			}
		}
		User user=userServiceImpl.getUserById(UserUtils.getCurrentUserId().toString());
		model.addAttribute("userType", user.getUserType());
		if(user.getUserType().equals("SUPPLIER")){
			model.addAttribute("isShowDel", "false");
		}else{
			model.addAttribute("isShowDel", "true");
		}
		model.addAttribute("shopName", shopName);
		model.addAttribute("intAssociated", intAssociated);
		model.addAttribute("format", format);
		return resultPage("/biz/intent/intAdvertociated/view", model, request);
	}
	
	
	/**
	 * 通知供应商下载合同
	 * @param id
	 * @param model
	 * @return
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年5月23日
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "{id}/sendMessage")
	public String sendMessage(@PathVariable Long id,HttpServletRequest request, Model model) throws Exception {
		IntAssociated intAssociated = intAssociatedService.get(id);
		Long lastContractId =  intAssociated.getContractId();
		if(lastContractId !=null){
			AssociatedContract  lastContract = contractServce.get(lastContractId.toString());
			model.addAttribute("associated", lastContract);
		}
		SysBaseFormat format = sysBaseFormatService.getFormatByCode(intAssociated.getFormatId());
		StringBuilder shopName = new StringBuilder();
		List<IntAssshops>  assshopsList =  intAssociated.getIntAssshopsList();
		Long contractId =  intAssociated.getContractId();
		if(contractId != null){
			AssociatedContract  associated = contractServce.get(contractId.toString());
			if(associated!=null){
			model.addAttribute("associated", associated);
			associated.setVersionUrl("biz/intent/intAssociated/");
			}
		}
		if(assshopsList !=null && assshopsList.size()>0){
			for (int i = 0; i < assshopsList.size(); i++) {
				shopName.append(assshopsList.get(i).getShop());
				shopName.append(",");
			}
		}
		sendMessagePur(intAssociated);
		User user=userServiceImpl.getUserById(UserUtils.getCurrentUserId().toString());
		model.addAttribute("userType", user.getUserType());
		if(user.getUserType().equals("SUPPLIER")){
			model.addAttribute("isShowDel", "false");
		}else{
			model.addAttribute("isShowDel", "true");
		}
		model.addAttribute("shopName", shopName);
		model.addAttribute("intAssociated", intAssociated);
		model.addAttribute("format", format);
		return resultPage("/biz/intent/intAssociated/view", model, request);
	}
	

	
	private void sendMessagePur(IntAssociated intAssociated) throws Exception {
		List<String> targets = Lists.newArrayList();
		targets.add(intAssociated.getSupplierId().toString());
		TodoMessage toMessage = new TodoMessage();
		toMessage.setId(idGenerator.getUId());
		toMessage.setUrl("/biz/intent/intAssociated/"+intAssociated.getId()+"/view");   
		toMessage.setTitle("意向单号"+intAssociated.getIntentNo()+"附件已生成");
		toMessage.setTitleLink("/biz/intent/intAssociated/"+intAssociated.getId()+"/view");
		toMessage.setSource(MessageConstant.SOURCE_OSSP);
		toMessage.setMessageType(MessageConstant.TODO_TYPE_NOTIFY);
		toMessage.setContent(intAssociated.getSubject()+"附件已生成");
		toMessage.setContentTypeFlag(MessageConstant.TODO_CONTENT_TYPE_TEXT);
		toMessage.setCreateBy(UserUtils.getCurrentUserId().toString());
		toMessage.setCreateDate(new Date());
		toMessage.setPersonIds(targets);
		try {
			messageService.send(toMessage);
		} catch (Exception e) {
			// TODO: handle exception
		}
	
	}
	
	/**
	 * 删除
	 * @param id
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @author yanghao 
	 * @data 2014年5月23日
	 */
	@RequestMapping(value = "{id}/delete")
	public String delete(@PathVariable Long id, Model model,
			RedirectAttributes redirectAttributes) {
		intAssociatedService.remove(id);
		addMessage(redirectAttributes, "删除合同作废意向成功！");
		return "redirect:/biz/intent/intAssociated/list";
	}
	
	/**
	 * 获取意向洽谈记录
	 * @param intAssociated
	 * @param response
	 * @param model
	 * @return
	 * @author yanghao
	 * @data 2014年5月26日
	 */
	@RequestMapping(value = "getAssrecordsList")
	public String getList(Assrecords assrecords,HttpServletRequest request,HttpServletResponse response,Model model) {
		QueryFilter queryFilter = getQuerFilter(request,assrecords);
		Assinfo ssinfo = assrecords.getAssinfo();
		if(ssinfo !=null){
			queryFilter.addFilter("area", ssinfo.getArea(), QueryOP.EQUAL);
			queryFilter.addFilter("areaId",  ssinfo.getAreaId(), QueryOP.EQUAL);
			queryFilter.addFilter("supplierNo", ssinfo.getSupplierNo(), QueryOP.LIKE);
			queryFilter.addFilter("supplierName", ssinfo.getSupplierName(), QueryOP.LIKE);
			queryFilter.addFilter("negotiationType", ssinfo.getNegotiationType(), QueryOP.EQUAL);
			queryFilter.addFilter("store", ssinfo.getStore(), QueryOP.EQUAL);
			queryFilter.addFilter("storeId",  ssinfo.getStoreId(), QueryOP.EQUAL);
			queryFilter.addFilter("floor", ssinfo.getFloorId(), QueryOP.EQUAL);
			queryFilter.addFilter("floorId",  ssinfo.getFloorId(), QueryOP.EQUAL);
		}
		queryFilter.addFilter("status", ContractUtils.NEG_STATUS_TJ, QueryOP.EQUAL);
		queryFilter.addFilter("contractType", ContractUtils.CONTRACT_TYPE_LY, QueryOP.EQUAL);
		queryFilter.addFilter("isUpToStandard",  assrecords.getIsUpToStandard(), QueryOP.EQUAL);
		Page<Assrecords> page = (Page<Assrecords>) assrecordService.find(queryFilter);
		int totalSize = (page.getTotal() + page.getPageSize() - 1) / page.getPageSize();
		model.addAttribute("page", page);
		model.addAttribute("totalSize", totalSize);
		model.addAttribute("assrecords", assrecords);
		return resultPage("/biz/intent/intAssociated/modal", model, request);
	}
	/**
	 * 获取意向洽谈记录(分页)
	 * @param assrecords
	 * @param request
	 * @param response
	 * @param model
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年5月26日
	 */
	@RequestMapping(value = "getAssrecordsListPage")
	public void getListPage(Assrecords assrecords,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		QueryFilter queryFilter = getQuerFilter(request,assrecords);
		String supplierNo = request.getParameter("supplierNo");
		String supplierName = request.getParameter("supplierName");
		String negotiationType = request.getParameter("negotiationType");
		StringBuilder sb = new StringBuilder();
		if(supplierNo !=null && "" != supplierNo){
			queryFilter.addFilter("supplierNo", supplierNo, QueryOP.LIKE);
		}
		if(supplierName !=null && "" !=supplierName){
			queryFilter.addFilter("supplierName", supplierName, QueryOP.EQUAL);
		}
		queryFilter.addFilter("negotiationType", negotiationType, QueryOP.EQUAL);
		queryFilter.addFilter("status", ContractUtils.NEG_STATUS_TJ, QueryOP.EQUAL);
		Page<Assrecords> page = (Page<Assrecords>) assrecordService.find(queryFilter);
		List<Assrecords> assrecordsList = page.getList();
		sb.append("{\"total\":\""+page.getTotal()+"\",");
		sb.append("\"pageNo\":\""+page.getPageNo()+"\",");
		sb.append("\"pageSize\":\""+page.getPageSize()+"\",");
		sb.append("\"jsonRoot\":[");
		for(int i = 0;i<assrecordsList.size();i++){
			Assrecords assrecord = assrecordsList.get(i);
			Assinfo info = assrecord.getAssinfo();
			String negotiation_Type = SysDictUtils.getValue("CONTRATC_ATTRIBUTE", info.getNegotiationType());
			String is_Modify_Contract =SysDictUtils.getValue("YESORNO", info.getIsModifyContract());
			if(is_Modify_Contract ==null){
				is_Modify_Contract = "";
			}
			sb.append("{");
			sb.append("\"id\":\""+assrecord.getId()+"\",");
			sb.append("\"number\":\""+info.getNumber()+"\",");
			sb.append("\"supplierNo\":\""+info.getSupplierNo()+"\",");
			sb.append("\"supplierName\":\""+info.getSupplierName()+"\",");
			sb.append("\"area\":\""+info.getArea()+"\",");
			sb.append("\"store\":\""+info.getStore()+"\",");
			sb.append("\"negotiation_Type\":\""+negotiation_Type+"\",");
			sb.append("\"is_Modify_Contract\":\""+is_Modify_Contract+"\"");
			sb.append("}");
			if(i<assrecordsList.size()-1){
				sb.append(",");
			}
		}
		sb.append("]}");
		out.write(sb.toString());
		out.flush();
		out.close();
	}
	
	/**
	 * 导入意向到合同信息
	 * @param model
	 * @return
	 * @author yangh
	 * @throws Exception 
	 * @data 2014年4月19日
	 */
	@RequestMapping(value = "{id}/insertToContract")
	public void insertToContract(@PathVariable Long id,Model model,HttpServletResponse response,HttpServletRequest request,RedirectAttributes redirectAttributes) throws Exception{
	
		String navId = request.getParameter("navId");
		response.setCharacterEncoding("utf-8");
		PrintWriter out =  response.getWriter();
		StringBuilder sb = new StringBuilder();
		try {
			AdvertAssociated associatedContract = new AdvertAssociated();
			intAdvertociatedService.saveToContract(id,associatedContract);
			Map map = new HashMap();
			map.put("id", id);
			map.put("isCreateContract", ContractUtils.IS_CONTRACT_MODIFY_YES);
			intAssociatedService.updateIsCreateContract(map);//设置为已导入合同
			sb.append("{\"success\":true}");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			sb.append("{\"success\":false}");
		}
		out.write(sb.toString());
		out.flush();out.close();
	}
	/**6
	 * 编辑意向结算及分成条款
	 * @param model
	 * @param request
	 * @param baseJson
	 * @param operate
	 * @param num
	 * @param redirectAttributes
	 * @return
	 * @author yanghao
	 * @data 2014年6月10日
	 */
	@RequestMapping(value = "editModalBase")
	public String editModalBase(Model model,HttpServletRequest request,String baseJson,String operate,String num,RedirectAttributes redirectAttributes){
		String _base=baseJson.replace("'", "\"").replace("@", "*").replace("#", "*");
		SimpleFilterProvider fp = new SimpleFilterProvider();
		fp.addFilter(
				"executeFilter",
				SimpleBeanPropertyFilter.serializeAllExcept(new String[] {
				 "createBy" }));
		IntAssbaseitems base =JacksonUtils.create().filter("myFilter", "id").json2Obj(_base, IntAssbaseitems[].class)[0];
		model.addAttribute("base", base);
		model.addAttribute("operate","edit");
		model.addAttribute("num",num);
		return "/biz/intent/intAssociated/modalBase";
	}
	/**
	 * 编辑（查看）意向合同条款
	 * @param model
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @author yanghao
	 * @data 2014年6月10日
	 */
	@RequestMapping(value = "editAssitems")
	public String editAssitems(Model model,String itemsJson,String operate,String num ,HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		String _items=itemsJson.replace("'", "\"");
		SimpleFilterProvider fp = new SimpleFilterProvider();
		fp.addFilter(
				"executeFilter",
				SimpleBeanPropertyFilter.serializeAllExcept(new String[] {
				 "createBy" }));
		IntAssitems items =JacksonUtils.create().filter("myFilter", "id").json2Obj(_items, IntAssitems[].class)[0];
		model.addAttribute("items", items);
		model.addAttribute("operate","edit");
		model.addAttribute("contractType", "marketassociated");
		model.addAttribute("num",num);
		return "/biz/intent/common/modalitems";
	}
	/**
	 * 选择要创建的版本
	 * @param mainId
	 * @param historyId
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 * @author yanghao
	 * @data 2014年6月11日
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "{mainId}/{historyId}/{id}/getMainVersion")
	public String getMainVersion(@PathVariable String mainId,@PathVariable String historyId,@PathVariable Long id,String intAssociatedId, HttpServletRequest request,Model model) {
		HashMap queryvalidate = new HashMap();
		String contractAttribute = request.getParameter("contractAttribute");
		queryvalidate.put("mainId", mainId);
		AdvertAssociated contract=iAdvertAssociatedService.getMainVersion(queryvalidate); 
		if(contract !=null){
			contract.setVersionUrl("biz/intent/intAdvertociated/");
			contract.setHistoryId(historyId);
			//创建“新版本”时，获取最新的版本信息返回verisonView.jsp页面
			model.addAttribute("version", contract);
		}
		
		model.addAttribute("intAssociatedId", intAssociatedId);
		model.addAttribute("contractAttribute", contractAttribute);
		return resultPage("/biz/intent/common/versionModal",model,request);
	} 
	
	/**
	 * 
	 * @param id
	 * @param historyId
	 * @param intAssociatedId
	 * @param navId
	 * @param request
	 * @param response
	 * @param assistId
	 * @param model
	 * @return
	 * @throws Exception
	 * @author yanghao
	 * @data 2014年6月11日
	 */
	@RequestMapping(value = "{id}/{historyId}/{intAssociatedId}/createNewVersion")
	public void createNewVersion(@PathVariable String id,@PathVariable String historyId,@PathVariable Long intAssociatedId,String navId,HttpServletRequest request,HttpServletResponse response,
			String assistId, Model model) throws Exception{

		String contractOperate = request.getParameter("contractAttribute");
		response.setCharacterEncoding("utf-8");
		PrintWriter out =  response.getWriter();
		StringBuilder sb = new StringBuilder();
		//合同变更，续签，新签，先生号
		//合同基本信息
		try {
			AdvertAssociated associated = iAdvertAssociatedService.createNewVersion(id,assistId,historyId);
			intAdvertociatedService.saveToContract(intAssociatedId,associated);
			Map map = new HashMap();
			map.put("id", intAssociatedId);
			map.put("isCreateContract", ContractUtils.IS_CONTRACT_MODIFY_YES);
			intAssociatedService.updateIsCreateContract(map);//设置为已导入合同
			sb.append("{\"success\":true}");
		} catch (Exception e) {
			// TODO: handle exception
			sb.append("{\"success\":false}");
		}
		out.write(sb.toString());
		out.flush();
		out.close();
	}
	
	
	@ResponseBody
	@RequestMapping(value = "{id}/sendToSap")
	public List<Object> sendToSap(@PathVariable String id,HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes redirectAttributes) throws Exception{
		request.setAttribute("id", id);
		String s_bean =request.getParameter("s_bean");
		StringBuffer sb = new StringBuffer();
		IDataBean dataBean = (IDataBean) ApplicationContextUtils.getBean(s_bean);
		RequestContext requestContext = new RequestContext(request);
		List<Object> dataList = dataBean.getDataList(requestContext);
		List<Object> messageList =Lists.newArrayList();
		for (Object object : dataList) {
			ResultSapVo vo =(ResultSapVo)object;
			sb.append(vo.getMenssage());
		}
		
		messageList.add(sb);
		return messageList ;
	}
	/**
	 *根據意向ID查看合同信息
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "getContarctByIntId")
	public String getContarctByIntId(Long id,HttpServletRequest request,Model model){
		String navId = request.getParameter("navId");
		AdvertAssociated associatedContract =iAdvertAssociatedService.getByIntId(id);
		return "redirect:/biz/contract/advertassociated/"+associatedContract.getId()+"/view?navId="+navId;
	}
	
}
